import { Component, Prop, Vue } from 'vue-facing-decorator';
import { BasicForm, useForm, UseFormReturnType } from '@/components/Form';
import { BasicModal, useModalInner, UseModalInnerReturnType } from '@/components/Modal';
import { formProps } from './dept.data';
import { getDeptList } from '@/api/demo/system';
import { computed, unref, ComputedRef, ref } from 'vue';

/**
 * @program: microservice-central-portal
 * @description: 部门管理
 * @author: baiHoo.chen
 * @create: 2022年5月24日
 **/
@Component({
  name: 'DeptModal',
  components: { BasicModal, BasicForm },
  emits: ['success', 'register'],
  setup() {
    return { isUpdate: ref(true) };
  },
})
export default class DeptModal extends Vue {
  formReturn: UseFormReturnType = useForm(formProps);
  modelReturn: UseModalInnerReturnType = useModalInner(this.callback);
  registerForm = this.formReturn[0];
  registerModal = this.modelReturn[0];
  @Prop({ type: Boolean, default: false }) isUpdate!: boolean;
  getTitle: ComputedRef<string> = computed(() => (!this.isUpdate ? '新增部门' : '编辑部门'));

  /**
   * 新增部门或编辑部门，表单提交
   */
  async handleSubmit(): Promise<void> {
    const { validate } = this.formReturn[1];
    const { setModalProps, closeModal } = this.modelReturn[1];
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      console.log(values);
      closeModal();
      this.$emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  /**
   * 弹出框回调
   * @param data
   */
  async callback(data: Recordable): Promise<void> {
    const { resetFields, setFieldsValue, updateSchema } = this.formReturn[1];
    const { setModalProps } = this.modelReturn[1];
    await resetFields();
    setModalProps({ confirmLoading: false });
    this.isUpdate = !!data?.isUpdate;

    if (unref(this.isUpdate)) {
      await setFieldsValue({
        ...data.record,
      });
    }
    const treeData = await getDeptList();
    await updateSchema({
      field: 'parentDept',
      componentProps: { treeData },
    });
  }
}
